'''
Created on Jun 20, 2012

@author: alebalbin
'''
import logging
import argparse
import sys
import os
import datetime
import subprocess
from collections import defaultdict
from lib.base import strandDNATree,transcriptome
from lib.parse_gtf2 import read_gtf

def build_it(gtf_file,outfile,ref_gtf=None):
    
    transc_types=['lincRNA','protein_coding','misc_RNA',
                 'polymorphic_pseudogene','misc_RNA_pseudogene',
                 'pseudogene', 'miRNA', 'processed_transcript',
                 'miRNA_pseudogene']
    
    gtf_file =open(gtf_file)
    mytrans=transcriptome()
    mydna=strandDNATree()    
    filter_transc=True
    of=open(outfile,'w')
    # First step create transcripts joining exons that belong to the
    # same transcript. 
    for transcript in read_gtf(gtf_file):
        #
        if transcript.feature_type=="transcript":
            #print transcript.chrom,transcript.start, transcript.end
            continue
        # If you provide a list of transcripts reference
        # the transcript should be in the reference to be considered
        inref=True
        if ref_gtf is not None:
            try:
                th=ref_gtf[transcript.annotation["transcript_id"]]
            except KeyError:
                inref=False
                #print transcript.annotation["transcript_id"]
                #continue
        if not inref:
            #print transcript.annotation["transcript_id"]
            continue
        
        mytrans.grow_transcriptome(transcript)
    gtf_file.close()
    
    # Second step: Split transcripts according to the strand that they are
    for tid,transcript in mytrans.transcripts_list.iteritems():
        #print tid
        mydna.grow_strand( transcript )
        
    # Third step look for overlapping transcripts in different strands.
    min_start_coord=0
    positive_strand=mydna.genome['+'] 
    sense_trans= positive_strand.find(min_start_coord,mydna.maxPosStrand)
    #print len(sense_trans)
    neg_strand='-'
    print outfile
    for t in sense_trans:
        nat_tot = mydna.sense_nat_pair(t,neg_strand)
        if nat_tot is not None:
            #print nat_tot
            of.write(",".join(map(str,nat_tot)).replace(',','\t')+"\n")
            #print ",".join(map(str,nat_tot)).replace(',','\t') 
    #print i

def read_samples_file(samples_file):
    '''
    '''
    myfiles=defaultdict()
    ifile=open(samples_file)
    for l in ifile:
        if l.startswith('#'):
            continue
        d=l.strip('\n').split('/')
        sample = d[7].split('.')[0] # in exds 6 this changes and it could be better to just fix the relation sample=file
        print sample
        myfiles[sample]=l.strip('\n')
    ifile.close()
    return myfiles



def main():
    '''
    '''
    logging.basicConfig(level=logging.DEBUG,
                        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    logging.info("==========================")
    parser = argparse.ArgumentParser()
    parser.add_argument("--g", dest="gtf_file", default=None)
    parser.add_argument("samples_file")
    args = parser.parse_args()
        
    if args.gtf_file is not None:
        ref_gtf_file=defaultdict()
        for transcript in read_gtf(open(args.gtf_file)):
            ref_gtf_file[transcript.annotation["transcript_id"]]="T" 
        #for transcript in read_gtf(open(args.gtf_file)):
        #    print transcript.feature
    else:
        ref_gtf_file=None
        
    samples_dict = read_samples_file(args.samples_file)
    for sp, gtf_file in samples_dict.iteritems():
        outfile=gtf_file+"snat.pairs.txt"
        print gtf_file
        build_it(gtf_file,outfile,ref_gtf_file)
        
if __name__ == '__main__': 
    sys.exit(main())

'''        
def read_gene_list(ifile):
    ifile=open(ifile)
    actionable_genes=deque()
    for l in ifile:
        fields = l.strip('\n').split('\t')
        start, end, value=int(fields[1]),int(fields[2]), {'chr':fields[0], 'annot':fields[3],'strand':fields[5]}
        actionable_genes.append( Gene(start, end, value) )
    
    return actionable_genes
    
       def __init__(self, int start, int end, object value=None, object chrom=None, object strand=None ):
        assert start <= end, "start must be less than end"


'''